jclass={
    initPage:function(){
        // 绑定dom对象
        this.obj = {
            searchText:$('#searchText'),
        };
        this.statesObj = [
            { value: 'circle', label: '圆形设置'},{ value: 'rectangle', label: '矩形设置'},
            { value: 'polygon', label: '多边形设置'},{ value: 'polyline', label: '线路设置'}
        ];
        // 声明全局变量
        this.data = {
            datatable:[],
            tableParams: {
                page:1,
                size:10,
                drawingType: '1', // 1-圆;2-正方形3-多边形;4-线路
                name: ''
            },
            map: {},
            mouseTool: {},
            mapEdit: {
                circleEditor: {}, ///圆形
                rectangleEditor: {}, // 矩形
                polyEditor: {}  // 多边形
            },
            mapEditDraw: {
                circle: {},
                rectangle: {},
                polygon: {},
                polyline: {}
            },
            overlays: [],
            drawTypeSelect: 'circle',
            tabSelectType: 1,
            addDrawAreaParams: {
                name: '',
                drawingType: '',
                longitude: '',
                latitude: '',
                radius: '',
                areaLonlat: '',
                strokeColor: '',
                strokeWeight: '',
                mileage: '',
                remark: ''
            }
        };
        this.getTableList();
        // this.creatTable({data:{},total:0});
        this.init();
        this.bindEvent();
    },
    init() {
        let that = this

        // 重置
        $("#resetClick").click(() => {
            $("#search_input_name").val("")
        })

        // 查询
        $("#searchClick").click(() => {
            this.getTableList()
        })

        this.mapInit()
    },
    mapInit() {
        let that = this
        this.data.map = new AMap.Map('jDdraw_map', {
            resizeEnable: true,
            zoom: 9,
            center: [108.93,34.27],
            mapStyle:'amap://styles/darkblue',

        });
        this.data.mouseTool = new AMap.MouseTool(this.data.map)
        this.data.mouseTool.on('draw',function(e){
            that.data.overlays.push(e.obj);
            console.log(that.data.overlays)
            let points = ''
            if (that.data.tabSelectType === 1) {
                points = `${that.data.overlays[0].getCenter().lng},${that.data.overlays[0].getCenter().lat},${that.data.overlays[0].getRadius()}`
            } else {
                let str2 = ''
                that.data.overlays[0].getPath().forEach(item => {
                    str2 += item.lng + "|" + item.lat + ','
                })
                points = str2.slice(0,str2.length-1)
            }
            $("#dialog_input_point").val(points)
            that.data.map.remove(that.data.overlays)
            // 画完就可编辑
            switch(that.data.tabSelectType){
                case 1: 
                    editCircle(that.data.overlays[0].getCenter().lng,that.data.overlays[0].getCenter().lat,that.data.overlays[0].getRadius());
                    break;
                case 2: 
                    editRectangle(points);
                    break;
                case 3: 
                    editPoly('poly',points)
                    break;
                case 4:
                    editPoly('line',points)
                    break;
                default: 
                    break;
            }

            this.close(false) // 关闭绘图 mouseTool.close(true)关闭绘图并删除图形
        })
    },
    draw(){
        if (this.data.overlays && this.data.overlays.length > 0) return
        switch(this.data.drawTypeSelect){
            case 'polyline': // 线
                this.data.mouseTool.polyline({
                  strokeColor:'#80d8ff'
                });
                break;
            case 'polygon': // 多边形
                this.data.mouseTool.polygon({
                  fillColor:'#00b0ff',
                  strokeColor:'#80d8ff'
                });
                break;
            case 'rectangle': // 矩形
                this.data.mouseTool.rectangle({
                  fillColor:'#00b0ff',
                  strokeColor:'#80d8ff'
                });
                break;
            case 'circle': // 圆
                this.data.mouseTool.circle({
                  fillColor:'#00b0ff',
                  strokeColor:'#80d8ff'
                });
                break;
        }
    },
    deleteDraw() {
        this.data.map.remove(this.data.overlays)
        this.data.overlays = [];
        this.data.map.clearMap()
        $("#dialog_input_point").val("")
    },
    bindEvent() {
        let that = this
        $("#jtab2 ul li").click(function(){
            let index = $(this).index();
            that.data.tabSelectType = $(this).data("type")
            $(this).addClass("active").siblings("li").removeClass("active");
            that.getTableList()
        })
        $("#draw_type_select").change(function() {
            that.data.drawTypeSelect = $("#draw_type_select option:selected").val()
            that.deleteDraw()
        })

        $("#add_btn").click(() => {
            openDialog();
            // $("#dialog_title").text("添加区域围栏")
            // $("#jmap_tools").html(`<div class="iconfont" id="btn_bind_draw">&#xe64b;</div>
            //         <div class="iconfont" id="btn_edit_ok">&#xe601;</div>
            //         <div class="iconfont" id="btn_delete_draw">&#xe613;</div>`)
            $("#jmap_tools").html(`<div class="iconfont" id="btn_bind_draw">&#xe64b;</div>
                    <div class="iconfont" id="btn_draw_center">&#xe64c;</div>`)
            $("#btn_bind_draw").click(() => {
                this.draw()
            })

            $("#btn_delete_draw").click(() => {
                this.deleteDraw()
            })
        })

        $("#add_dialog_submit").click(() => {
            if (!$("#dialog_input_point").val()) {
                // Jdialog.alert("请画一个区域")
                JPop.alert({msg:'请画一个区域'})
                return false
            } else {
                let dataform = $("#form_weilan").serializeArray()
                let a = true
                console.log(dataform)
                dataform.forEach(item => {
                    if(!item.value) a=false
                })
                if(a) {
                    let obj = this.data.overlays[0]
                    // console.log(obj)
                    this.addSubmit(obj)
                    return false
                }
            }
            
            
        })

        $("#jDdraw_map")

        
    },
    getTableList() {
        this.data.tableParams.drawingType = this.data.tabSelectType
        this.data.tableParams.name = $("#search_input_name").val()
        jrequest.get("/api/fenceArea",this.data.tableParams).then(res => {
            this.data.datatable = res.data
            $("#jtable_line").bootstrapTable('destroy');
            this.creatTable(res)
            // $("#jtable_line").bootstrapTable('load',res.data);
        })
    },
    // 添加围栏
    addSubmit(obj) {
        switch(this.data.tabSelectType) {
            case 1:
                // this.data.addDrawAreaParams.longitude = obj.getCenter().lng
                // this.data.addDrawAreaParams.latitude = obj.getCenter().lat
                // this.data.addDrawAreaParams.radius = obj.getRadius() 

                console.log($("#dialog_input_point").val())
                this.data.addDrawAreaParams.longitude = $("#dialog_input_point").val().split(',')[0]
                this.data.addDrawAreaParams.latitude = $("#dialog_input_point").val().split(',')[1]
                this.data.addDrawAreaParams.radius = $("#dialog_input_point").val().split(',')[2]
                break;
            case 4:
                // let str = ''
                // obj.getPath().forEach(item => {
                //     str += item.lng + "|" + item.lat + ','
                // })
                // this.data.addDrawAreaParams.strokeColor = obj.strokeColor
                // this.data.addDrawAreaParams.strokeWeight = obj.strokeWeight
                // this.data.addDrawAreaParams.areaLonlat = str.slice(0,str.length-1)
                this.data.addDrawAreaParams.areaLonlat = $("#dialog_input_point").val()
                break;
            default: 
                // let str2 = ''
                // obj.getPath().forEach(item => {
                //     str2 += item.lng + "|" + item.lat + ','
                // })
                // this.data.addDrawAreaParams.areaLonlat = str2.slice(0,str2.length-1)
                this.data.addDrawAreaParams.areaLonlat = $("#dialog_input_point").val()
                break;
        }
        this.data.addDrawAreaParams.drawingType = this.data.tabSelectType
        this.data.addDrawAreaParams.name = $("#d_input_name").val()
        this.data.addDrawAreaParams.remark = $("#dialog_input_ms").val()
        // console.log(this.data.addDrawAreaParams)
        // if ($("#dialog_title").text() === '编辑区域围栏') {
        if ($("#dialog_title").text().search('编辑') !== -1) {
            jrequest.put("/api/fenceArea",this.data.addDrawAreaParams).then(res => {
                if (res) {
                    JPop.alert({msg:'修改成功！',type:'success'})
                    closeDialog()
                    this.getTableList()
                }
            })
        } else {
            this.data.addDrawAreaParams.id = ''
            jrequest.post("/api/fenceArea",this.data.addDrawAreaParams).then(res => {
                if (res) {
                    JPop.alert({msg:'添加成功！',type:'success'})
                    closeDialog()
                    this.getTableList()
                }
            })
        }
        
    },
    tableEvent:function(id,data,columns,paginationShow,total){
        data.forEach(item => {
            item.Button = this.operateFormatter()
        })
        let that = this
        $('#' + id).bootstrapTable({
            method: 'get',
            cache: false,
            height: 320,
            pagination: paginationShow,
            pageSize: that.data.tableParams.size,
            pageNumber:that.data.tableParams.page,
            striped: true,
            columns: columns,
            sidePagination: 'server', // client or server
            totalRows: total,
            data :data,
            onPageChange: function (size, number) {
                console.log(number)
                that.data.tableParams.page = number
                that.data.tableParams.size = size
                that.getTableList()
            },
            formatNoMatches: function(){
                return '暂无数据';
            }
        });
    },
    creatTable:function(res){
        var self=this;
        var columnsOne = [
            {
                title : '序号',
                align: "center",
                formatter: function (value, row, index) {
                    //获取每页显示的数量
                    var pageSize=self.data.tableParams.size;
                    //获取当前是第几页
                    var pageNumber=self.data.tableParams.page;
                    //返回序号，注意index是从0开始的，所以要加上1
                    return pageSize * (pageNumber - 1) + index + 1;
                }
            },
            {
              field: "name",
              title: "名称"
            },
            {
              field: "createUserName",
              title: "创建用户"
            },
            {
              field: "createTime",
              title: "创建时间"
            },
            {
                field: 'Button',
                title: '操作',
                width: "150",
                align: 'center',
                events: operateEvents,
            }
        ];
        self.tableEvent("jtable_line",res.data,columnsOne,true,res.total);
    },
    operateFormatter() {
        return [
            '<button type="button" id="table_del">删除</button>',
            '<button type="button" id="table_edit">修改</button>'
        ].join('');
    }
}

$(function(){
    jclass.initPage();

    // 表格操作按钮
    window.operateEvents = {
        'click #table_del': (e,value,row,index) => {
            // console.log(row)
            
            // Jdialog.confirm({ message: `确定删除${row.name}?` }).on(function (e) {
            //     if (e) {
            //         jrequest.delete(`/api/fenceArea/${row.id}`,{}).then(res => {
            //             if(res) {
            //                 jclass.getTableList()
            //             }
            //         })
            //     }
            // });
            JPop.dialogDel({msg:'确定删除?',operate:true}).on(success => {
                if (success) {
                    jrequest.delete(`/api/fenceArea/${row.id}`,{}).then(res => {
                        if(res) {
                            jclass.getTableList()
                        }
                    })
                }
            })
        },
        'click #table_edit': (e,value,row,index) => {
            console.log(row)
            jclass.data.addDrawAreaParams.id = row.id
            openDialog()
            $("#dialog_input_ms").val(row.remark)
            $("#d_input_name").val(row.name)
            let obj = jclass.statesObj[Number(jclass.data.tabSelectType)-1]
            $("#dialog_title").text(`编辑${obj.label}`)
            // $("#jmap_tools").html(`<div class="iconfont" id="btn_edit_draw">&#xe64b;</div><div class="iconfont" id="btn_edit_ok">&#xe601;</div>`)
            $("#jmap_tools").html(`<div class="iconfont" id="btn_draw_center">&#xe64c;</div>`)
            switch(jclass.data.tabSelectType){
                case 1: 
                    editCircle(row.longitude,row.latitude,row.radius);
                    $("#dialog_input_point").val(`${row.longitude},${row.latitude},${row.radius}`)
                    break;
                case 2: 
                    editRectangle(row.areaLonlat);
                    $("#dialog_input_point").val(`${row.areaLonlat}`)
                    break;
                case 3: 
                    editPoly('poly',row.areaLonlat)
                    $("#dialog_input_point").val(`${row.areaLonlat}`)
                    break;
                case 4:
                    editPoly('line',row.areaLonlat)
                    $("#dialog_input_point").val(`${row.areaLonlat}`)
                    break;
                default: 
                    break;
            }
            // editCircle()
            // editRectangle(row.areaLonlat)
            // editPoly('poly')
        }
    }
});
// 编辑圆形
function editCircle(longitude,latitude,radius) {
     jclass.data.mapEditDraw.circle = new AMap.Circle({
        center: [longitude, latitude],
        radius: radius, //半径
        strokeColor:'#80d8ff',
        strokeDasharray: [30,10],
        strokeStyle: 'dashed',
        fillColor:'#0d4a66',
        fillOpacity:0.5,
        cursor:'pointer',
        zIndex:50
    })

    jclass.data.mapEditDraw.circle.setMap(jclass.data.map)
    // 缩放地图到合适的视野级别
    jclass.data.map.setFitView([ jclass.data.mapEditDraw.circle ])

    jclass.data.mapEdit.circleEditor = new AMap.CircleEditor(jclass.data.map, jclass.data.mapEditDraw.circle)
    jclass.data.mapEdit.circleEditor.open()

    $("#btn_draw_center").click(() => {
        jclass.data.map.setFitView([ jclass.data.mapEditDraw.circle ])
    })

    // $("#btn_edit_ok").click(() => {
    //     jclass.data.mapEdit.circleEditor.close()
    // })
    // $("#btn_edit_draw").click(() => {
    //     jclass.data.mapEdit.circleEditor.open()
    // })

    // 移动圆心监听
    jclass.data.mapEdit.circleEditor.on('move', function(event) {
        // event.target 即为编辑后的圆形对象
        let points = `${event.target.getCenter().lng},${event.target.getCenter().lat},${event.target.getRadius()}`
        $("#dialog_input_point").val(points)
    })
    // 调整半径监听
    jclass.data.mapEdit.circleEditor.on('adjust', function(event) {
        // event.target 即为编辑后的圆形对象
        let points = `${event.target.getCenter().lng},${event.target.getCenter().lat},${event.target.getRadius()}`
        $("#dialog_input_point").val(points)
    })

}
// 编辑矩形
function editRectangle(path) {
    // path = '108.855842|34.429618,109.053596|34.429618,109.053596|34.307195,108.855842|34.307195'
    path = path.split(",")

    var southWest = new AMap.LngLat(path[1].split("|")[0],path[1].split("|")[1])
    var northEast = new AMap.LngLat(path[3].split("|")[0],path[3].split("|")[1])

    var bounds = new AMap.Bounds(southWest,northEast)

    jclass.data.mapEditDraw.rectangle = new AMap.Rectangle({
        bounds: bounds,
        strokeColor:'#80d8ff',
        strokeDasharray: [30,10],
        strokeStyle: 'dashed',
        fillColor:'#0d4a66',
        fillOpacity:0.5,
        cursor:'pointer',
        zIndex:50
    })

    jclass.data.mapEditDraw.rectangle.setMap(jclass.data.map)
    // 缩放地图到合适的视野级别
    jclass.data.map.setFitView([ jclass.data.mapEditDraw.rectangle ])

    jclass.data.mapEdit.rectangleEditor = new AMap.RectangleEditor(jclass.data.map, jclass.data.mapEditDraw.rectangle)
    jclass.data.mapEdit.rectangleEditor.open()

    $("#btn_draw_center").click(() => {
        jclass.data.map.setFitView([ jclass.data.mapEditDraw.rectangle ])
    })

    // $("#btn_edit_ok").click(() => {
    //     jclass.data.mapEdit.rectangleEditor.close()
    // })
    // $("#btn_edit_draw").click(() => {
    //     jclass.data.mapEdit.rectangleEditor.open()
    // })

    // 调整举行矩形监听
    jclass.data.mapEdit.rectangleEditor.on('adjust', function(event) {
        // console.log(event.target.getPath())
        // event.target 即为编辑后的多边形对象
        let str2 = ''
        event.target.getPath().forEach(item => {
            str2 += item.lng + "|" + item.lat + ','
        })
        $("#dialog_input_point").val(str2.slice(0,str2.length-1))
    })
}
// 编辑多边形or线
function editPoly(type, path) {
    // path = [
    //     [116.403322, 39.920255],
    //     [116.410703, 39.897555],
    //     [116.402292, 39.892353],
    //     [116.389846, 39.891365]
    // ]
    let arr = path.split(",")
    arr.forEach((item,index) => {
        arr[index] = item.split("|")
    })
    console.log(arr)
    path = arr
    if (type === 'line') {
        jclass.data.mapEditDraw.polyline = new AMap.Polyline({
            path: path,
            strokeColor:'#80d8ff',
            strokeDasharray: [30,10],
            strokeStyle: 'dashed',
            fillColor:'#0d4a66',
            fillOpacity:0.5,
            cursor:'pointer',
            zIndex:50
        })

        jclass.data.mapEditDraw.polyline.setMap(jclass.data.map)
        // 缩放地图到合适的视野级别
        jclass.data.map.setFitView([ jclass.data.mapEditDraw.polyline ])
        jclass.data.mapEdit.polyEditor = new AMap.PolyEditor(jclass.data.map, jclass.data.mapEditDraw.polyline)
    } else if(type === 'poly') {
        jclass.data.mapEditDraw.polygon = new AMap.Polygon({
            path: path,
            strokeColor:'#80d8ff',
            strokeDasharray: [30,10],
            strokeStyle: 'dashed',
            fillColor:'#0d4a66',
            fillOpacity:0.5,
            cursor:'pointer',
            zIndex:50
        })

        jclass.data.map.add(jclass.data.mapEditDraw.polygon)
        // 缩放地图到合适的视野级别
        jclass.data.map.setFitView([ jclass.data.mapEditDraw.polygon ])
        jclass.data.mapEdit.polyEditor = new AMap.PolyEditor(jclass.data.map, jclass.data.mapEditDraw.polygon)
    }

    jclass.data.mapEdit.polyEditor.open()

    $("#btn_draw_center").click(() => {
        jclass.data.map.setFitView([ jclass.data.mapEditDraw.polygon ])
    })

    // $("#btn_edit_ok").click(() => {
    //     jclass.data.mapEdit.polyEditor.close()
    // })
    // $("#btn_edit_draw").click(() => {
    //     jclass.data.mapEdit.polyEditor.open()
    // })
    
    jclass.data.mapEdit.polyEditor.on('addnode', function(event) {
        // console.log(event.target.getPath())
        // event.target 即为编辑后的多边形对象
        let str2 = ''
        event.target.getPath().forEach(item => {
            str2 += item.lng + "|" + item.lat + ','
        })
        $("#dialog_input_point").val(str2.slice(0,str2.length-1))
    })
    jclass.data.mapEdit.polyEditor.on('adjust', function(event) {
        // console.log(event.target.getPath())
        // event.target 即为编辑后的多边形对象
        let str2 = ''
        event.target.getPath().forEach(item => {
            str2 += item.lng + "|" + item.lat + ','
        })
        $("#dialog_input_point").val(str2.slice(0,str2.length-1))
    })
    jclass.data.mapEdit.polyEditor.on('removenode', function(event) {
        // console.log(event.target.getPath())
        // event.target 即为编辑后的多边形对象
        let str2 = ''
        event.target.getPath().forEach(item => {
            str2 += item.lng + "|" + item.lat + ','
        })
        $("#dialog_input_point").val(str2.slice(0,str2.length-1))
    })
}
function openDialog() {
    // console.log(statesObj[Number(jclass.data.tabSelectType)-1].value)
    let obj = jclass.statesObj[Number(jclass.data.tabSelectType)-1]
    // jdSelect.JdSelectRadioInit('#dselect_draw_type',[{name:obj.label,val:obj.value}],(select) => {
    //     jclass.data.drawTypeSelect = select.val
    //     jclass.deleteDraw()
    // })
    // $("#draw_type_select").html(`<option value=${obj.value}>画${obj.label}</option>`)
    $("#dialog_title").text(`添加${obj.label}`)
    jclass.data.drawTypeSelect = obj.value
    $("#driverlineDialog").show()
}
function closeDialog() {
    $("#driverlineDialog").hide()
    $("#d_input_name").val("")
    $("#dialog_input_point").val("")
    $("#dialog_input_ms").val("")
    jclass.deleteDraw()
    jclass.data.map.remove(jclass.data.mapEditDraw.circle)
    jclass.data.map.remove(jclass.data.mapEditDraw.rectangle)
    jclass.data.map.remove(jclass.data.mapEditDraw.polygon)
    jclass.data.map.remove(jclass.data.mapEditDraw.polyline)
    jclass.data.map.clearMap()
    
}

